import { useState,useEffect,useRef } from "react"

function Stopwatch() {

    const [isRunning,setIsRunning] = useState(false)
    const [time,setTime] = useState(0)
    const intervalRef = useRef(null)
    const startTime = useRef(0)

    useEffect(()=>{
        if(isRunning === true){
            intervalRef.current = setInterval(()=>{
                setTime(Date.now() - startTime.current)
            },10)
        }
        return()=>{
            clearInterval(intervalRef.current)
        }
    },[isRunning])

    function run(){
        setIsRunning(true)
        startTime.current = Date.now() - time
        console.log(startTime.current)
    }

    function stop(){
        setIsRunning(false)
    }

    function reset(){
        setTime(0)
        setIsRunning(false)
    }


    function formatTime(){
        let hours = Math.floor(time / (1000*60*60))
        let mins = Math.floor(time / (1000*60) % 60) 
        let secs = Math.floor(time / 1000 % 60)
        let millsecs =  Math.floor(time % 1000 /10)

        hours = String(hours).padStart(2,"0");
        mins = String(mins).padStart(2,"0");
        secs = String(secs).padStart(2,"0");
        millsecs = String(millsecs).padStart(2,"0");

        return `${hours}:${mins}:${secs}:${millsecs}`
    }

    return(
        <div className="stopwatch">
            <div className="display">
                {formatTime()}
            </div>
            <div className="controls"> 
                <button className="start-button" onClick={run}>Start</button>
                <button className="stop-button" onClick={stop}>Stop</button>
                <button className="reset-button" onClick={reset}>reset</button>
            </div>
        </div>
    )

}

export default Stopwatch